package com.sgb.kjwl;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.GetPhoneInfoListener;
import com.chuanglan.shanyan_sdk.listener.InitListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.aspectj.login.ILogin;
import com.sgb.kjwl.aspectj.login.LoginSDK;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.view.ui.activity.self.authentication.CertificationActivity;
import com.sgb.link.router.PathLogin;
import com.swgk.core.base.permission.MPermission;
import com.swgk.core.base.permission.annotation.OnMPermissionDenied;
import com.swgk.core.base.permission.annotation.OnMPermissionGranted;
import com.swgk.core.base.permission.annotation.OnMPermissionNeverAskAgain;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.widget.ActionBar;
import com.swgk.core.base.BaseActivity;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.helper.AppManagerHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.takephoto.app.TakePhoto;
import com.swgk.core.takephoto.app.TakePhotoActivity;
import com.swgk.core.takephoto.app.TakePhotoImpl;
import com.swgk.core.takephoto.compress.CompressConfig;
import com.swgk.core.takephoto.model.InvokeParam;
import com.swgk.core.takephoto.model.LubanOptions;
import com.swgk.core.takephoto.model.TContextWrap;
import com.swgk.core.takephoto.model.TResult;
import com.swgk.core.takephoto.model.TakePhotoOptions;
import com.swgk.core.takephoto.permission.InvokeListener;
import com.swgk.core.takephoto.permission.PermissionManager;
import com.swgk.core.takephoto.permission.TakePhotoInvocationHandler;
import com.im.immodel.IMUtils;
import com.swgk.core.util.LogUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * Description:
 * Author zhengkewen
 * Time 2017/12/11
 */
public class AppActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener {
    private static final int BASIC_PERMISSION_REQUEST_CODE = 100;
    private static final String[] BASIC_PERMISSIONS = new String[]{
//            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
//            android.Manifest.permission.READ_EXTERNAL_STORAGE,
//            android.Manifest.permission.RECORD_AUDIO,
//            android.Manifest.permission.CAMERA,
//            android.Manifest.permission.READ_PHONE_STATE,
            android.Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    public static final String[] BASIC_EXTERNAL_STORAGE = new String[]{
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.READ_EXTERNAL_STORAGE
    };

    private static final String TAG = TakePhotoActivity.class.getName();
    protected TakePhoto takePhoto;
    private InvokeParam invokeParam;
    protected ActionBar mActionBar;
    protected View mAllView;
    protected View mErrorView;
    protected View mDisplayView;
    protected View mBottomView;
    public Bundle msavedInstanceState;

    /**
     * activity堆栈管理
     */
    protected AppManagerHelper appManager = AppManagerHelper.getAppManagerHelper();

    @Override
    protected void initView() {

    }

    @Override
    protected void init() {

    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {

    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected boolean exit() {
        return false;
    }

    @Override
    protected boolean registerNet() {
        return false;
    }

    @Override
    protected void connectNetWork() {

    }

    @Override
    protected void disconnectNetWork() {

    }

    @Override
    public void onMultiClick(View v) {

    }

    public Context getActivity() {
        return this;
    }

    ILogin iLogin = new ILogin() {
        @Override
        public void login(Context applicationContext, int userDefine) {
            switch (userDefine) {
                case 0:
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, "");
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PC_TOKEN, "");
                    com.swgk.core.common.utils.ActivityJump.startActivity(PathLogin.VerificationCodeLoginActivity);
                    break;
                case 1:
                    Toast.makeText(applicationContext, "您还没有登录，请登陆后执行", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    Toast.makeText(applicationContext, "执行失败，因为您还没有登录！", Toast.LENGTH_SHORT).show();
                    break;
            }
        }

        @Override
        public boolean isLogin(Context applicationContext) {
            return !"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.resourcePCToken, ""));
        }

        @Override
        public void clearLoginStatus(Context applicationContext) {
            SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.resourcePCToken, "");
        }

        @Override
        public void realName(Context applicationContext, int realDefine) {
            switch (realDefine) {
                case 0:
                    new RoundDialog.Builder(applicationContext)
                            .title("温馨提示")
                            .content("您还未进行实名认证")
                            .cancel("取消")
                            .confirm("去认证")
                            .contentGravity(Gravity.CENTER)
                            .cancelable(false)
                            .confirmCallback(v -> CertificationActivity.start(applicationContext, "1"))
                            .show();
                    break;
                case 1:
                    Toast.makeText(applicationContext, "您还没有实名，请实名后执行", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    Toast.makeText(applicationContext, "执行失败，因为您还没有实名！", Toast.LENGTH_SHORT).show();
                    break;
            }
        }

        @Override
        public boolean isReal(Context applicationContext) {
            return SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        msavedInstanceState = savedInstanceState;
        // 添加activity 到栈
        appManager.addActivity(this);

        mActionBar = findViewById(R.id.action_bar);
        mAllView = findViewById(R.id.success_view);
        mErrorView = findViewById(R.id.error_view);
        mDisplayView = findViewById(R.id.display_view);
        mBottomView = findViewById(R.id.bottom_view);
        if (mActionBar !=null){
            mActionBar.setOnBackClickListener(v -> finish());
        }

        LoginSDK.getInstance().init(this, iLogin);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 从栈中移除activity
        DialogHelper.dismissProgressDialog();
        appManager.finishActivity(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        pictureSelectorResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
        checkingPermission();
    }

    /**
     * 授权完成
     */
    public void checkingPermission(){

    }

    /***************************************************手机相册***********    在onCreate中设置 getTakePhoto().onCreate(savedInstanceState);***********************************/

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    protected TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        configCompress(takePhoto);
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        LogUtil.i(TAG, "takeSuccess：" + result.getImage().getCompressPath());
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {
        LogUtil.i(TAG, getResources().getString(R.string.msg_operation_canceled));
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    /**
     * 设置手机屏幕亮度变暗
     */
    protected void lightoff() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.3f;
        getWindow().setAttributes(lp);
    }

    /**
     * 设置手机屏幕亮度显示正常
     */
    protected void lighton() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1f;
        getWindow().setAttributes(lp);
    }

    /**
     * 设置参数
     *
     * @param takePhoto
     */
    protected void configCompress(TakePhoto takePhoto) {
        takePhoto.onEnableCompress(null, false);
        int maxSize = 102400;
        int width = 800;
        int height = 800;
        boolean showProgressBar = false;// 不显示压缩进度条
        boolean enableRawFile = true;// 拍照后保存原图 true
        CompressConfig config;
        boolean IsColltor = true; //用自带的还是用第三方的  true 自带  false 第三方
        if (IsColltor) {
            config = new CompressConfig.Builder().setMaxSize(maxSize)
                    .setMaxPixel(width >= height ? width : height)
                    .enableReserveRaw(enableRawFile)
                    .create();
        } else {
            LubanOptions option = new LubanOptions.Builder().setMaxHeight(height).setMaxWidth(width).setMaxSize(maxSize).create();
            config = CompressConfig.ofLuban(option);
            config.enableReserveRaw(enableRawFile);
        }
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(false);    // 使用TakePhoto自带相册：
        builder.setCorrectImage(true); //纠正拍照的照片旋转角度
        takePhoto.setTakePhotoOptions(builder.create());
        takePhoto.onEnableCompress(config, showProgressBar);
    }

    /**
     * 需要判断是否是Android8.0版本
     */
    /*public void checkIsAndroidO() {
        if (Build.VERSION.SDK_INT >= 26) {
            boolean b = getPackageManager().canRequestPackageInstalls();
            if (b) {
                dialog.doUpdate();//安装应用的逻辑(写自己的就可以)
            } else {
                Uri packageURI = Uri.parse("package:com.sgb.kjwl");
                //注意这个是8.0新API
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                startActivityForResult(intent, 6006);
            }
        } else {
            dialog.doUpdate();
        }
    }*/
    //改变状态栏字体颜色  防止沉侵式 状态栏看不清字
    private static void setAndroidNativeLightStatusBar(Activity activity, boolean dark) {
        View decor = activity.getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    protected void requestBasicPermission() {
        MPermission.printMPermissionResult(true, this, BASIC_PERMISSIONS);
        MPermission.with(this)
                .setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS)
                .request();
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {
        MPermission.printMPermissionResult(false, this, BASIC_PERMISSIONS);
    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
        try {
            MToast.showToast(this, "未全部授权，部分功能可能无法正常运行！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        MPermission.printMPermissionResult(false, this, BASIC_PERMISSIONS);
    }

    protected void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }

    //阿里播放器状态栏特殊机型
    protected boolean isStrangePhone() {
        boolean strangePhone = "mx5".equalsIgnoreCase(Build.DEVICE)
                || "Redmi Note2".equalsIgnoreCase(Build.DEVICE)
                || "Z00A_1".equalsIgnoreCase(Build.DEVICE)
                || "hwH60-L02".equalsIgnoreCase(Build.DEVICE)
                || "hermes".equalsIgnoreCase(Build.DEVICE)
                || ("V4".equalsIgnoreCase(Build.DEVICE) && "Meitu".equalsIgnoreCase(Build.MANUFACTURER))
                || ("m1metal".equalsIgnoreCase(Build.DEVICE) && "Meizu".equalsIgnoreCase(Build.MANUFACTURER));

        return strangePhone;
    }

    //闪验
    protected static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE
    };

    /**
     * 初始化闪验sdk
     */
    public void initShanyan() {
        OneKeyLoginManager.getInstance().init(getApplicationContext(), "qSzIzzlq", "4IwLLfH8", new InitListener() {
            @Override
            public void getInitStatus(int code, String result) {
                if (code == 1022) {
                    //预取号,先判断用户是否已登录，若已登录则不进行预取号

                    //申请动态权限
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        //6.0以上运行时权限处理
                        EsayPermissions.with(AppActivity.this).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                            @Override
                            public void hasPermission(List<String> granted, boolean isAll) {
                                getPrepareMobile();
                            }

                            @Override
                            public void noPermission(List<String> denied, boolean quick) {
                                getPrepareMobile();
                            }
                        });

                    } else {
                        //有权限
                        getPrepareMobile();
                    }
                }
            }
        });
    }

    /**
     * 闪验预取号
     */
    private void getPrepareMobile() {
        OneKeyLoginManager.getInstance().getPhoneInfo(new GetPhoneInfoListener() {
            @Override
            public void getPhoneInfoStatus(int code, String result) {
                if (code == 1022) {
                    //预取成功
                    MkvUtils.get().putBoolean(MkvUtils.CommomData, CacheMarker.ShanYan,true);
                } else {
                    MkvUtils.get().putBoolean(MkvUtils.CommomData, CacheMarker.ShanYan,false);
                }
            }
        });
    }

    /**
     * 检查手机上是否安装了指定的软件
     *
     * @param context
     * @param packageName：应用包名
     * @return
     */
    protected boolean isAvilible(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        List<String> packageNames = new ArrayList<String>();
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        return packageNames.contains(packageName);
    }

    /**
     * 调用高德地图
     *
     * @param
     * @return
     */
    protected void jumpGaoDeMap(double latitude, double longitude, String address) {
        String url = "androidamap://navi?sourceApplication=appname&poiname=" + address + "&lat=" + latitude + "&lon=" + longitude + "&dev=1&style=2";
        Intent intent = new Intent("android.intent.action.VIEW",
                android.net.Uri.parse(url));
        startActivity(intent);
    }

    /**
     * 调用百度地图
     *
     * @param
     * @return
     */
    protected void jumpBaiDuMap(double latitude, double longitude) {
        String url = "baidumap://map/navi?location=" + latitude + "," + longitude + "$coord_type=bd09ll&src=andr.baidu.openAPIdemo";
        Intent intent = new Intent("android.intent.action.VIEW",
                android.net.Uri.parse(url));
        startActivity(intent);
    }

    /**
     * 调用腾讯地图
     *
     * @param
     * @return
     */
    protected void jumpTenXunMap(double startLatitude, double startLongitude, String startAddress, double endLatitude, double endLongitude, String endAddress) {
        String url = "qqmap://map/routeplan?type=drive&from=" + startAddress + "&fromcoord=" + startLatitude + "," + startLongitude + "&to=" + endAddress + "&tocoord=" + endLatitude + ", " + endLongitude + "&referer=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77";
        Intent intent = new Intent("android.intent.action.VIEW",
                android.net.Uri.parse(url));
        startActivity(intent);
    }

    /**
     * 调用本地相册获取相册照片(调用pictureSelector()方法后再实现onPictureSelectorResult方法来获取图片的回调)
     *
     * @param isCompress  是否压缩图片
     * @param size        最小压缩图片的的大小
     * @param number      还能选择图片的数量
     */
    protected void pictureSelector(boolean isCompress, int size, int number) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .selectionMode(PictureConfig.MULTIPLE)
                .isCompress(isCompress)
                .minimumCompressSize(size)
                .maxSelectNum(number)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    /**
     * 调用本地相册获取相册照片(调用pictureSelector()方法后再实现pictureSelectorResult方法来获取图片的回调)
     *
     * @param isCompress  是否压缩图片
     * @param size        最小压缩图片的的大小
     * @param number      还能选择图片的数量
     * @param requestCode 请求code用来判断多次图片获取的位置
     */
    protected void pictureSelector(boolean isCompress, int size, int number, int requestCode) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .selectionMode(PictureConfig.MULTIPLE)
                .isCompress(isCompress)
                .minimumCompressSize(size)
                .maxSelectNum(number)
                .forResult(requestCode);
    }

    /**
     * 获取本地相册照片的回调(调用pictureSelector()方法后再实现onPictureSelectorResult方法来获取图片的回调)
     *
     * @param
     * @return
     */
    protected void pictureSelectorResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST){
            onPictureSelectorResult(PictureSelector.obtainMultipleResult(data));
        }
    }

    /**
     * 获取本地相册照片的回调(调用pictureSelector()方法后再实现onPictureSelectorResult方法来获取图片的回调)
     *
     * @param
     * @return
     */
    protected void onPictureSelectorResult(List<LocalMedia> selectList) {

    }

    /**
     * 进入IM单聊界面(该方法在调用之前必须先判断用户的登录状态)
     *
     * @param toAccount 对方用户(单聊)的IM账号
     * @return
     */
    protected void buildSingleTalking(String toAccount) {
        IMUtils.getInstance().buildSingleTalking(toAccount);
    }

    /**
     * 设置沉浸状态栏下的title
     *
     * @param isImplement
     */
    protected void setTileImmerse(boolean isImplement) {
        if (isImplement) {
            TitleImmerse.assistActivity(findViewById(android.R.id.content));

        }
    }

    /**
     * 清除页面焦点
     */
    protected void clearAllFocus() {
        if (getCurrentFocus() != null) {
            getCurrentFocus().clearFocus();
        }
    }

//    @Override
//    protected void loading() {
//
//    }
//
//    @Override
//    protected void error() {
//
//    }
    @Override
    public void loading() {
        if (mAllView != null && mErrorView != null){
            mAllView.setVisibility(View.GONE);
            mErrorView.setVisibility(View.GONE);
        }
    }

    @Override
    public void error() {
        if (mErrorView != null && mAllView != null){
            mAllView.setVisibility(View.VISIBLE);
            mErrorView.setVisibility(View.VISIBLE);
            if (mDisplayView != null){
                mDisplayView.setVisibility(View.GONE);
            }

            if (mBottomView != null){
                mBottomView.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void success() {
        if (mErrorView != null && mAllView != null){
            mAllView.setVisibility(View.VISIBLE);
            mErrorView.setVisibility(View.GONE);
        }
    }
}
